package com.mugui.base.client.net.baghandle;

import com.mugui.base.base.Autowired;
import com.mugui.base.base.Component;
import com.mugui.base.client.net.auto.AutoTask;
import com.mugui.base.client.net.bagsend.WsHandle;
import com.mugui.base.client.net.base.Task;
import com.mugui.base.client.net.task.TaskCycleImpl;
import com.mugui.base.util.Other;
import com.mugui.bean.JsonBean;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

import java.util.concurrent.ConcurrentHashMap;

@Component
@Task
@AutoTask
public class PongTask extends TaskCycleImpl<PongTask.PongMsgBean> {


    private ConcurrentHashMap<String, PongTask.PongMsgBean> concurrentHashMap = new ConcurrentHashMap<>();


    @Setter
    @Getter
    private int out_time = 10000;


    @Getter
    @Setter
    private int max_out_time = 30000;

    @Override
    protected void handle(PongMsgBean poll) {
        PongMsgBean pongMsgBean = concurrentHashMap.get(poll.id);
        if (pongMsgBean == null) {
            return;
        }
        if (poll.create_time + max_out_time < System.currentTimeMillis()) {
            System.out.println("超时：" + PongTask.class.getName());
            return;
        }
        if (poll.last_time + out_time > System.currentTimeMillis()) {
            int i = (int) (poll.last_time + out_time - System.currentTimeMillis());
            if (i > 0) {
                Other.sleep(i);
            }
            getCycleList().addFirst(poll);
            return;
        }
        System.out.println("发送超时，标记过期 " + poll.data);
        poll.enhancedWebSocketClient.expire();
        poll.enhancedWebSocketClient = new EnhancedWebSocketClient(poll.sendQueue.getServerUrl(), 3);
        poll.enhancedWebSocketClient.sendMessage(poll.sendQueue, poll.data);
        poll.last_time = System.currentTimeMillis();
        super.add(poll);
    }

    @Override
    public void add(PongMsgBean data) {
        concurrentHashMap.put(data.id, data);
        super.add(data);
    }


    public void remove(String id) {
        concurrentHashMap.remove(id);
    }


    @Getter
    @Setter
    @Accessors(chain = true)
    public static final class PongMsgBean {

        String id;

        String data;


        EnhancedWebSocketClient enhancedWebSocketClient;

        WsHandle.SendQueue sendQueue;

        final long create_time = System.currentTimeMillis();

        long last_time = create_time;
    }

}
